package Linux五种IO模型;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;

/**
 * @author coderFu
 * @create 2022/3/6
 * NIO 服务端
 */
public class NIOServer2 {

    public static void main(String[] args) throws IOException {

        // 得到服务端的serverSocketChannel 对象
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //创建监听对象 选择器
        Selector selector = Selector.open();

        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.bind(new InetSocketAddress(9091));

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){

            if (selector.select(2000) == 0){
                //轮询 两秒内没有客户端链接
                continue;
            }
            // 得到SelectionKey 对象 进行事件的判定
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if (key.isAcceptable()){
                    System.out.println("有人来链接");
                    ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                    // 获取网络通道
                    SocketChannel clientChannel = serverChannel.accept();
                    clientChannel.configureBlocking(false);
                    clientChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()){
                    // 读取客户端的信息
                    SocketChannel channel = (SocketChannel)key.channel();

                    // 获取连带的缓冲区对象
                    ByteBuffer attachment = (ByteBuffer) key.attachment();
                    // 写入数据
                    channel.read(attachment);

                    // 逻辑关于 array 开始
                    byte[] array = new byte[attachment.position()];
                    if (array.length > 0){
                        // 复制元素到 array
                        System.arraycopy(attachment.array(),0,array,0,array.length);
                        System.out.println(Arrays.toString(array));
                    }
                    // 逻辑array结束
                    attachment.put("你好".getBytes());
                    attachment.flip();
                    channel.write(attachment);

                    // 清空
                    attachment.clear();

                }
                iterator.remove();
            }


        }
    }
}
